//判斷一個月是30天還是31天
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
function isWeekday(year, month, day) {
var day = new Date(year, month, day).getDay();
return day !=0 && day !=6;
}
// 判定輸入日期是周幾?
//getDay:一個型其中的第幾天 0代表星期日
function getWeekdaysInMonth(month, year) {
var days = daysInMonth(month, year); //這裡daysInMonth是第一個function
var weekdays = 0;
for(var i=0; i< days; i++) {
if (isWeekday(year, month, i+1)) //這裡isWeekday是第2個function
weekdays++;
}
return weekdays;
}
//算是一周的哪一天,因為週日是0,所以每一筆要+1
//將全部input內部取出的字串,按下按鈕會觸發取得value
function calculateSalary() {
const totalSalary = parseFloat(document.getElementById("totalSalary").value); //取得輸入日期 把薪水轉換成浮點數,因為number從input取出一律是字串, 經過parseFloat轉換,型別變成number
const startDate = new Date(document.getElementById("startDate").value); //工作開始日期
const endDate = new Date(document.getElementById("endDate").value); //工作結束日期
const extraHoliday = parseFloat(document.getElementById("extraHoliday").value); //是指例假日嗎?
//這段是包在觸發按鈕內的
if (startDate.getMonth() !== endDate.getMonth()) {
alert("Start date and end date must be in the same month."); //避免起始月和結束越不一樣
return;
}
const weekdaysInMonth = getWeekdaysInMonth(
startDate.getMonth(), //startDate是之前宣告的變數
startDate.getYear()
) - extraHoliday
let currentDate = new Date(startDate);
let weekdays = 0;
while (currentDate <= endDate) {
if (currentDate.getDay() >= 1 && currentDate.getDay() <= 5) {
weekdays++;
}
currentDate.setDate(currentDate.getDate() + 1);
}
const salaryPerDay = totalSalary / weekdaysInMonth;
const resultDiv = document.getElementById("result"); //結果輸出
const totalSalaryInRange = salaryPerDay * (weekdays - extraHoliday);
resultDiv.innerHTML = Total Salary for the selected range: ${totalSalaryInRange.toFixed(2)}
; //toFixed
}